package wz

import (
	"fmt"
	"github.com/go-resty/resty/v2"
	"navi-mumbai/common/xerr"
	"net/http"
	"strconv"
	"time"
)

type BalanceReq struct {
	User     string `json:"user"`     // B端用户名称 用户注册账户 邮箱取@之前 最大64字节
	Uid      string `json:"uid"`      // B端用户ID
	Currency string `json:"currency"` // 币种
}

type BalanceData struct {
	Username string `json:"username"`
	Balance  string `json:"balance"`
	Currency string `json:"currency"`
}

type BalanceResp struct {
	Code int         `json:"code"`
	Data BalanceData `json:"data"`
}

const balanceURI = "wzgames/wallet/balance"

func (r *HttpClient) Balance(req *BalanceReq) (resp *BalanceResp, err error) {
	// md5
	stamp := strconv.FormatInt(time.Now().Unix(), 10)
	sign := md5v(r.Id + req.User + req.Uid + req.Currency + stamp + r.Secret)
	resp = &BalanceResp{}
	var rsp *resty.Response
	rsp, err = r.cli.R().SetHeader("Accept", "application/json").SetQueryParams(map[string]string{
		"operator": r.Id,
		"user":     req.User,
		"uid":      req.Uid,
		"currency": req.Currency,
		"stamp":    stamp,
		"sign":     sign,
	}).SetResult(resp).SetError(resp).Get(r.Host + balanceURI)
	if err != nil {
		return
	}
	if rsp.IsError() {
		err = xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, rsp.Status())
		return
	}
	if resp.Code != http.StatusOK {
		err = xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, fmt.Sprintf("code:%d", resp.Code))
		return
	}
	return
}
